package 复习.博客.回溯算法.组合问题;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 组合总和2 {
    List<List<Integer>> lists = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    int Target;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        boolean[] flag = new boolean[candidates.length];
        Target = target;
        backStacking(candidates,flag,0,0);
        return lists;
    }

    public void backStacking(int[] candidates,boolean[] flag,int index,int sum){
        if(sum == Target){
            lists.add(new ArrayList<>(list));
        }
        for(int i = index;i < candidates.length && sum + candidates[i] <= Target;i++){
            if(i > 0 && candidates[i] == candidates[i - 1] && flag[i - 1] == false){
                continue;
            }
            list.add(candidates[i]);
            flag[i] = true;
            backStacking(candidates,flag,i,sum + candidates[i]);
            flag[i] = false;
            list.remove(list.size() - 1);
        }
    }
}
